package com.example.xcService.pojo.channels.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.pojo.response.CardData;
import com.example.pojo.response.CardInfo;
import com.example.xcService.pojo.channels.ChannelResult;
import com.example.xcService.pojo.channels.ChannelService;
import com.example.xcService.pojo.tool.HttpTool;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.util.DigestUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class Plugin_ECARD_P024 implements ChannelService {
    @Override
    public ChannelResult QueryBalance(JSONObject apiConfig) {
        System.out.println("成功调用了QueryBalance");
        return  ChannelResult.success("success");
    }


    @Override
    public ChannelResult Submit(JSONObject apiConfig, Map<String, Object> data) {

        try {
            String SUPProductId=String.valueOf(data.get("SUPProductId"));
            DateTimeFormatter dtf=DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
            String timeMillis=dtf.format(LocalDateTime.now());
            BigDecimal PurchasePrice=new BigDecimal(String.valueOf(data.get("PurchasePrice")));
            BigDecimal money=PurchasePrice.multiply(new BigDecimal(100)).setScale(0, RoundingMode.HALF_DOWN);
            LinkedHashMap<String, Object> params = new LinkedHashMap<>();
            params.put("quantity",1);
            params.put("phone",data.get("AccountVal"));
            params.put("orderFee",money);
            params.put("outerOrderId",data.get("ChannelOrderCode"));
            params.put("itemId",SUPProductId);
            params.put("timestamp",timeMillis);
            params.put("title",data.get("ProductName"));

            String appSecret = apiConfig.getString("AppSecret");
            String submitUrl = apiConfig.getString("SubmitUrl");
            String signStr="";
            signStr="outerOrderId="+data.get("ChannelOrderCode")+"&phone="+data.get("AccountVal")+"&timestamp="+timeMillis+appSecret;


            String sign = DigestUtils.md5DigestAsHex(signStr.getBytes());
            params.put("sign",sign);

            String req = HttpPost(submitUrl, params);
            JSONObject jsonObject = JSONObject.parseObject(req);
            String code = jsonObject.getString("code");
            String msg = jsonObject.getString("errorMsg");
            if (code.equals("200")) {
                return ChannelResult.IN_PROCESS("提单成功，权益充值中");
            }else if (code.equals("400")){
                return ChannelResult.error(msg);
            }
            return ChannelResult.FAILED(msg);
        }catch (Exception e) {
            e.printStackTrace();
            log.error("淘宝饿了么提交订单接口错误：",e);
            return  ChannelResult.error("淘宝饿了么提交订单接口错误");
        }
    }

    /*  UserId	是	string	会员身份标识（我方提供）
        TimesTamp	是	long	Unix时间戳（毫秒）
        UserOrderId	是	string	会员部订单号
        Sign	是	string	签名
    */

    @Override
    public ChannelResult Query(JSONObject apiConfig, Map<String, Object> data) {

        try {
            DateTimeFormatter dtf=DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
            String timeMillis=dtf.format(LocalDateTime.now());
            LinkedHashMap<String, Object> queryParams = new LinkedHashMap<>();
            queryParams.put("timestamp",timeMillis);
            queryParams.put("outerOrderId",data.get("ChannelOrderCode"));
            queryParams.put("phone",data.get("AccountVal"));

            String appSecret = apiConfig.getString("AppSecret");
            String queryUrl = apiConfig.getString("QueryUrl");
            String signStr="";
            signStr="outerOrderId="+data.get("ChannelOrderCode")+"&phone="+data.get("AccountVal")+"&timestamp="+timeMillis+appSecret;


            String sign = DigestUtils.md5DigestAsHex(signStr.getBytes());
            queryParams.put("sign",sign);

            String req = HttpPost(queryUrl, queryParams);
            JSONObject jsonObject = JSONObject.parseObject(req);
            String code = jsonObject.getString("code");
            String msg = jsonObject.getString("errorMsg");
            String reqData = jsonObject.getString("data");
            if (code.equals("200")) {
                JSONObject dataObj = JSONObject.parseObject(reqData);
                String orderStatus = dataObj.getString("status");
                if (orderStatus.equals("SUCCESS")) {
                    List<CardInfo> cardDataList=new ArrayList<>();
                    CardInfo cardData=new CardInfo();
                    cardData.setType(0);
                    cardData.setCode(dataObj.getString("voucherId"));
                    cardData.setKey(dataObj.getString("voucherId"));;
                    cardData.setEffstart(dataObj.getString("effectTime"));
                    cardData.setEffend(dataObj.getString("expireTime"));
                    cardDataList.add(cardData);
                    return ChannelResult.success(cardDataList,"充值成功");
                }
                if (orderStatus.equals("UNDERWAY")) {
                    return ChannelResult.IN_PROCESS("订单处理中");
                }
                return ChannelResult.FAILED(msg);
            }
            return ChannelResult.error(msg);
        }catch (Exception e) {
            e.printStackTrace();
            log.error("淘宝饿了么查询订单接口错误：",e);
            return  ChannelResult.error("淘宝饿了么查询订单接口错误");
        }
    }


    @Override
    public ChannelResult Notify(JSONObject apiConfig, Map<String, Object> data) {
        System.out.println("成功调用了Notify");
        return  ChannelResult.success("success");
    }

    public static String HttpPost(String url, Map<String,Object> param) {
        String result = "";
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        // 创建Post请求
        HttpPost httpPost = new HttpPost(url);

        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 设置ContentType(注:如果只是传普通参数的话,ContentType不一定非要用application/json)
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setEntity(new StringEntity(JSONObject.toJSONString(param),"utf-8"));
            log.info("httpPost请求："+url+"?"+JSONObject.toJSONString(param));
            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();

            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                result= EntityUtils.toString(responseEntity);
                log.info("httpPost请求返回："+JSONObject.toJSONString(result));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return  result;
    }
}
